package br.org.group.web.fortunes;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.org.group.android.dao.FortunesDAO;
import br.org.group.android.dao.ImportFortunes;
import br.org.group.android.dao.PMF;

@SuppressWarnings("serial")
public class FortunesWebServlet extends HttpServlet {

	private int id;
	private List<FortunesDAO> fortunes;
	private PersistenceManager pm = PMF.get().getPersistenceManager();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/xml; charset=utf-8");
		
		pm = PMF.get().getPersistenceManager();
		
		if(req.getParameter("id") != null){
			try{
			id = Integer.parseInt((String)req.getParameter("id"));
			}catch (Exception e) {
				id = 1;
			}
		}
		if(id < 0 ){
			id = id * -1;
		}
		if(id == 0 ){
			id = 1;
		}
		
/*		if((req.getParameter("clean") != null) && (req.getParameter("clean").equals("true"))){
			clean();
		}
		String q = "select from " + FortunesDAO.class.getName();
	    fortunes = (List<FortunesDAO>) pm.newQuery(q).execute();

		if(fortunes.isEmpty()){
	       popula();	
	    }
	    */
		
	   String query = "select from " + FortunesDAO.class.getName() + " where id == "+(id + 1);
	    fortunes = (List<FortunesDAO>) pm.newQuery(query).execute();
	    
	    if (fortunes.isEmpty()) {
	    	resp.getWriter().println(getXML(new FortunesDAO()));
	    	return;
	    }else{
	        for (FortunesDAO f : fortunes) {

	        	resp.getWriter().println(getXML(f));
	        	
	        }
	    }
    pm.close();
	}

	private String getXML(FortunesDAO f){
    	StringBuilder xml = new StringBuilder();
    	xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
    	xml.append("<FORTUNE>");
    	xml.append("<ID>");
    	xml.append(f.getId());
    	xml.append("</ID>");
    	xml.append("<MSG>");
    	xml.append(f.getMensagem().getValue());
    	xml.append("</MSG>");
    	xml.append("<AUTOR>");
    	xml.append(f.getAutor());
    	xml.append("</AUTOR>");
    	xml.append("<CATEGORIA>");
    	xml.append(f.getCategoria());
    	xml.append("</CATEGORIA>");
    	xml.append("</FORTUNE>");
    	return xml.toString();
	}
private void popula(){
    
    	ImportFortunes impFortunes = new ImportFortunes();
    	int n  = impFortunes.Popula();
    	//resp.getWriter().println("Populando.."+n);	
    
}
	private void clean(){
    if(( fortunes.size() > 0)){
			pm.deletePersistentAll(fortunes);
		
    }

}
}
